package com.xmall.product.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmall.product.define.request.spu.SpuDescRequest;
import com.xmall.product.utils.ConvertUtils;
import com.xmall.product.define.dto.spu.SpuDescDto;
import com.xmall.product.entity.SpuDesc;
import com.xmall.product.mapper.SpuDescMapper;
import com.xmall.product.service.ISpuDescService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 *  服务实现类
 */
@Service
public class SpuDescServiceImpl extends ServiceImpl<SpuDescMapper, SpuDesc> implements ISpuDescService {

    /**
     * 保存
     */
    @Override
    public void save(Long spuId, List<SpuDescRequest> descs) {
        if(CollectionUtil.isNotEmpty(descs)){
            descs.forEach(desc -> desc.setSpuId(spuId));
            this.saveBatch(ConvertUtils.SpuDescModule.INSTANCE.toEntityList(descs));
        }
    }

    /**
     * 更新
     */
    @Transactional
    @Override
    public void update(Long spuId, List<SpuDescRequest> descs) {
        this.remove(new QueryWrapper<SpuDesc>().eq("spu_id", spuId));
        this.save(spuId, descs);
    }

    /**
     * 删除
     */
    @Override
    public void delete(Long spuId) {
        this.remove(new QueryWrapper<SpuDesc>().eq("spu_id", spuId));
    }

    /**
     * spu描述信息
     */
    @Override
    public List<SpuDescDto> list(Long spuId) {
        List<SpuDesc> list = this.list(new QueryWrapper<SpuDesc>().eq("spu_id", spuId));
        return ConvertUtils.SpuDescModule.INSTANCE.toDtoList(list);
    }

    @Override
    public List<String> imageList(Long spuId) {
        return this.list(spuId).stream().sorted(Comparator.comparing(SpuDesc::getSort)).map(SpuDesc::getUrl).collect(Collectors.toList());
    }
}
